/*===== code build by mstore0.1.3 =====*/

/*===== common/base#config:0 =====*/

var $stylepath = '/style/';

/*===== common/base#js:0 =====*/

function $$(namespace, factory, module){
    
    if(typeof namespace == 'function'){ //定义块执行
        var wrapper = function(fn){
            if(typeof fn != 'function'){
                return function(){};
            }
            return fn;
        };
        var $it = {
            click: function(fns){
                this.listen('click', fns);
            },
            listen: function(type, events){
                $.each(events, function(key, event){
                    $(document).on(type, '[jhand="'+ key +'"]', wrapper(event));
                });
            },
            extend: function(methods){
                $.each(methods, function(key, method){
                    if(!$it[key]){
                        $it[key] = wrapper(method);
                    }
                });
            },
            ajax: function(ajaxs){
                var $ajax = $it.ajax;
                $.each(ajaxs, function(key, ajax){
                    $ajax[key] = wrapper(ajax);
                });
            },
            tpl: function(tpls){
                var $tpl = $it.tpl;
                $.each(tpls, function(key, tpl){
                    $tpl[key] = wrapper(tpl);
                });
            }
        };
        
        $it.tasks = initTasks();
        
        namespace($it);
        $it.init && $it.init();
        $it.domready && $($it.domready);
        return;
    }
    
    function initTasks(){
        
        var itTask;
        'wait,then,error,end'.replace(/\w+/g, function(name){
            tasks[name] = function(){
                initItTask();
                return itTask[name].apply(itTask, arguments);
            };
        });
        
        return tasks;
        
        function tasks(initFn){
            if(typeof initFn == 'function'){
                initFn(new Task);
            }else{
                return new Task;
            }
        }
        
        function Task(){
            
            var that = this;
            
            var queue = [];
            var queueTimer;
            var rejectObject;
            var rejectCallback;
            var endCallback;
            var waitLength = 0;
            
            that.then = then;
            that.wait = wait;
            that.resolve = resolve;
            that.reject = reject;
            that.error = error;
            that.end = end;
            
            function startTask(){
                clearTimeout(queueTimer);
                queueTimer = setTimeout(nextTask);
            }
            
            function nextTask(){
                
                if(rejectObject){
                    rejectCallback && rejectCallback.call(that, rejectObject.data);
                    endCallback && endCallback.call(that);
                    return;
                }
                
                var queueItem = queue.shift();
                if(typeof queueItem == 'function'){ //同步任务
                    queueItem.call(that, that.reject, that);
                    nextTask();
                }else if(queueItem){ //异步任务
                    waitLength = queueItem.length;
                    for(var i = 0; i < queueItem.length; i++){
                        queueItem[i].call(that, that.resolve, that.reject, that);
                    }
                }else{
                    endCallback && endCallback.call(that);
                }
                
            }
            
            function resolve(){
                if(--waitLength == 0){ //全部已触发
                    nextTask();
                }
            }
            
            function reject(data){
                rejectObject = {
                    data: data
                };
                nextTask();
            }
            
            function then(fn){
                queue.push(fn);
                startTask();
                return that;
            }
            
            function wait(fn){
                var asyncQueueFns;
                if(arguments.length > 1){ //多个任务并行
                    asyncQueueFns = [].slice.call(arguments); 
                }else if(typeof fn == 'function'){ //单个任务
                    asyncQueueFns = [fn];
                }else{ //数组形式传入多个任务
                    asyncQueueFns = fn.slice();
                }
                queue.push(asyncQueueFns);
                startTask();
                return that;
            }
            
            function error(fn){
                rejectCallback = fn;
                return that;
            }
            
            function end(fn){
                endCallback = fn;
            }
            
        }
        
        function initItTask(){
            if(!itTask){
                itTask = new Task;
            }
            return itTask;
        }
        
    }
    
    module = module || $$;
    
    //定义新模块
    var prevmodule; //上一级模块
    var nextkey; //下一级模块的key
    namespace.replace(/[^.]+/g, function(key){
        prevmodule = module;
        nextkey = key;
        module = module[key] = module[key] || {};
    });
    
    var exports = typeof factory == 'function' ? factory() : factory;
    
    if(typeof exports == 'function' || {}.toString.call(exports) == '[object Array]'){ //传入的是函数或数组时，直接覆盖旧的模块
        prevmodule[nextkey] = exports;
    }else if({}.toString.call(exports) == '[object Object]'){ //传入的是对象，对旧模块进行遍历扩充
        for(var key in exports){
            module[key] = exports[key];
        }
    }
    
}

$$('info', function(){
    return function(data){
        if(window.console && window.console.info){
            if(console.info.apply){ //ie8下console.info.apply方法不存在
                console.info.apply(null, arguments);
            }else{
                console.info(data);
            }
        }
    };
});

$$('domready', function(){
    return function(selector, callback){
        $(function(){
            $(selector)[0] && callback()
        })
    }
});

function $xz(namespace, factory){
    $$(namespace, factory, $xz);
}

/*===== common/base#rtpl:0 =====*/

$rtpl = function(){

var utils = {
    $escape: escape,
    $tostring: tostring,
    $each: foreach
};

return rtpl;

function rtpl(str, data){
    
    //从函数注释内提取模板
    if(typeof str == 'function'){
        str = (str +'').match(/\/\*([\w\W]+)\*\//)[1];
    }
    
    data = data || {};

    var lines = [];
    
    foreach(
        str
            .replace(/\{\{\{/g, '{{')
            .replace(/\}\}\}/g, '}}')
            .replace(/\r/g, '')
            .split(/\n/g),
        function(line){
            if(/^\s*\{\{.+?\}\}\s*$/.test(line)){
                lines.push(trim(line));
            }else{
                lines.push(line+'\r\n');
            }
        } 
        
    );
       
    str = lines.join('');
    
    str = str
        .replace(/<zstoreToken:clientOpenFlag>/g, '{{')
        .replace(/<zstoreToken:clientCloseFlag>/g, '}}')
        .replace(/<zstore_module [^>]*>/g, '')
        .replace(/<\/zstore_module>/g, '');

    var uniq = {$data:1, $out:1};
    
    var p1 = '$out.push(';
    var p2 = ');';
    
    var header = 'var ';
    var body = '$out = [];';
    var footer = 'return $out.join("")';
    
    foreach(str.split('{{'), function(code){
        
        code = code.split('}}');
        
        if(code.length == 1){
            body += html(code[0]);
        }else{
            body += makejs(code[0]);
            if(code[1]){
                body += html(code[1]);
            }
        }
    
    });
    
    var code = header + body + footer;

    try{
        return format(trim(Function("$utils", "$data", code)(utils, data)));
    }catch(e){
        throw e;
    }
    
    function html(code){
        return p1 + stringify(code) + p2 +'\n';
    }
    
    function makejs(code){

        code = parse(code);
        
        foreach(getVariable(code), function(name){
            
            if(uniq[name]){
                return;
            }

            var value;
                
            // 声明模板变量
            // 赋值优先级:
            // utils > data
            if (utils[name]) {
                value = "$utils." + name;
            }else if(name in data){
                value = "$data." + name;
            }else{
                value = 'undefined';
            }
            
            header += name + "=" + value + ",";
            
            uniq[name] = true;
            
        });
        
        return code + "\n";
    }
    
    //分析逻辑指令
    function parse(code){
    
        var split = code.split(' ');
        var key = split.shift();
        var args = split.join(' ');
        
        switch(key){
            
            case 'if':
            
                code = 'if('+ args +'){';
                break;
                
            case 'else':
            
                if (split.shift() == 'if') {
                    code = '}else if('+ split.join(' ') +'){';
                } else {
                    code = '}else{';
                }
                break;

            case '/if':

                code = '}';
                break;
                
            case 'each':
                
                var object = split[0] || '$data';
                var as     = split[1] || 'as';
                var value  = split[2] || '$value';
                var index  = split[3] || '$index';
                
                var param   = value +','+ index;
                
                if (as != 'as') {
                    object = '[]';
                }
                
                code =  '$each('+ object +',function('+ param +'){';
                break;

            case '/each':

                code = '});';
                break;
                
            case 'break':
                code = 'return false;';
                break;
            case 'continue':
                code = 'return;';
                break;
                
            case 'module':
                //console.info(args)
                var zstorepath_zstoredata = args.split(' ');
                var zstorepath = zstorepath_zstoredata.shift();
                var zstoredata = zstorepath_zstoredata.join(' ');
                
                if(zstoredata){
                    zstoredata = trim(zstoredata)
                        .replace(/\\\\/g, '\\')
                        .replace(/\\\{/g, '{')
                        .replace(/\\\}/g, '}')
                        ;
                        
                }

                if(zstoredata){
                    code = '$out.push(function(){ try{ var $it = '+zstoredata+';}catch(e){return "<error>";} try{var $out = [];';
                }else{
                    code = '$out.push(function($it, $out){$it = {};try{$out = [];';
                }
                
                break;
            case '/module':
                code = ' return $out.join("");}catch(e){return "<error>";} }());';
                break;
            case 'script':
                code = '';
                break;
            default:
                
                if(/^#/.test(key)){
                    code = "$tostring("+ code.substr(1) +")";
                }else{
                    code = "$escape("+ code +")";
                }

                code = p1 + code + p2;
        }
        
        return code;
        
    }
    
    function trim(str){
        return str.replace(/^\s+|\s$/g, '');
    }
    
}

function escape(str){
    return tostring(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
}

function tostring(str){
    if(str == null){
        return '';
    }
    return ''+ str;
}

function foreach(data, callback){
    if({}.toString.call(data) == '[object Array]'){
        for(var i = 0; i < data.length; i++){
            callback.call(data, data[i], i, data);
        }
    }else{
        for (var i in data) {
            callback.call(data, data[i], i);
        }
    }
}

function stringify(str){
    return "'"+ (''+ str)
    .replace(/('|\\)/g, '\\$1')
    .replace(/\r/g, '\\r')
    .replace(/\n/g, '\\n') + "'";
}

//获取模板中的变量名
function getVariable(code){
    
    var KEYWORDS =
        // 关键字
        'break,case,catch,continue,debugger,default,delete,do,else,false'
        + ',finally,for,function,if,in,instanceof,new,null,return,switch,this'
        + ',throw,true,try,typeof,var,void,while,with'

        // 保留字
        + ',abstract,boolean,byte,char,class,const,double,enum,export,extends'
        + ',final,float,goto,implements,import,int,interface,long,native'
        + ',package,private,protected,public,short,static,super,synchronized'
        + ',throws,transient,volatile'

        //+ ',Math'
        
        // ECMA 5 - use strict
        + ',arguments,let,yield'

        + ',undefined';

    var REMOVE_RE = /\/\*[\w\W]*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|"(?:[^"\\]|\\[\w\W])*"|'(?:[^'\\]|\\[\w\W])*'|\s*\.\s*[$\w\.]+/g;
    var SPLIT_RE = /[^\w$]+/g;
    var KEYWORDS_RE = new RegExp(["\\b" + KEYWORDS.replace(/,/g, '\\b|\\b') + "\\b"].join('|'), 'g');
    var NUMBER_RE = /^\d[^,]*|,\d[^,]*/g;
    var BOUNDARY_RE = /^,+|,+$/g;
    var SPLIT2_RE = /^$|,+/;

    // 获取变量
    getVariable = function(code){
        return code
        .replace(REMOVE_RE, '')
        .replace(SPLIT_RE, ',')
        .replace(KEYWORDS_RE, '')
        .replace(NUMBER_RE, '')
        .replace(BOUNDARY_RE, '')
        .split(SPLIT2_RE);
    };
    
    return getVariable(code);
}

function format(code){ //格式化对齐缩进
    var 
    lineText = code.split('\n'),
    linePadding = Array(30).join(' ');
    for(var i = 1; i < lineText.length; i++){
        
        if(/^\s*$/.test(lineText[i])){ //过滤空行
            continue;
        }
        
        var curPadding = lineText[i].match(/^\s*/)[0];
        if(curPadding){
            linePadding =
                curPadding.length < linePadding.length
                ? curPadding
                : linePadding;
        }else{
            linePadding = '';
            break;
        }
        
    }
    
    return code.replace(RegExp('^'+linePadding, 'mg'), '');
}

}();

/*===== common/base#localstorage:0 =====*/

$$('localstorage', function(){
    
    if(!window.localStorage){
        return function(){};
    }
    
    return exports;
    
    function exports(key, value){ //支持储存数字，布尔值，JSON对象
        if(value === undefined){
            var value = localStorage.getItem(key);
            if(value != null && /^\[\[\[(JSON|BOOL|NUMB)\]\]\]:/.test(value)){
                var source = value.match(/^\[\[\[(JSON|BOOL|NUMB)\]\]\]:(.+)/);
                var dataType = source[1];
                var dataValue = source[2];
                value = ({
                    JSON: function(){
                        return JSON.stringify(dataValue);
                    },
                    BOOL: function(){
                        return dataValue == 'true' ? true : false;
                    },
                    NUMB: function(){
                        return parseFloat(dataValue);
                    }
                })();
            }
            return value;
        }else if(value == null){
            localStorage.removeItem(key);
        }else{
            if(typeof value == 'number'){
                value = '[[[NUMB]]]:'+ value;
            }else if(typeof value == 'object'){
                value = '[[[JSON]]]:'+ JSON.stringify(value);
            }else if(typeof value == 'boolean'){
                value = '[[[BOOL]]]:' + value;
            }
            localStorage.setItem(key, value);
        }
    }
});   

/*===== common/base#window:0 =====*/

$$('window', function(){
    
    var pid = 0;
    var openLength = 0; //当前打开的窗口数量
    var options = {}; //多例配置
    var exports = {
        open: open,
        alert: alert,
        confirm: confirm
    };
    
    var OVERFLOW_Y = $('html').css('overflow-y'); //默认的overflow属性
    var SCROLL_WIDTH;
    $(function(){
        SCROLL_WIDTH = getScrollSize(); //滚动条宽度
    });
    
    $(document).on('click', '[jbtn="jqWindow.close"],[jbtn="jqWindow.submit"]', function(e){
        ({
            'jqWindow.close': close,
            'jqWindow.submit': submit
        })[$(this).attr('jbtn')]($(this).parents('.jqWindow'), this);
        
    });
    
    $(window).on('resize', function(){
        if(openLength){
            $.each(options, function(pid, option){
                setPosition(option.$window);
            });
        }
    });
    
    return exports;
    
    function open(content, option){
        
        option = option || {};
        openLength++;
        
        var $container = $($rtpl(function(){/*
            <div data-pid="{{pid}}" class="jqWindow {{clsName ? ''+ clsName : ''}}">
                <div class="masklayer"></div>
                {{if closeButton == 'outer'}}<i class="outerCloseButton icon-close" jbtn="jqWindow.close"></i>{{/if}}
                <div class="jqWindowWrapper">
                    <div class="jqWindowPanel">
                        {{if closeButton == 'inner'}}<i jbtn="jqWindow.close" class="innerCloseButton icon-close"></i>{{/if}}
                        {{if title}}<div class="title"><em style="display:block">{{title}}</em></div>{{/if}}
                        <div class="jqWindowContent">
                            {{#content}}
                            {{if buttonStyle}}
                                <div class="buttonbox {{buttonStyle}}Style"><b jbtn="jqWindow.submit" class="ok">确定</b><b jbtn="jqWindow.close" class="close">取消</b></div>
                            {{/if}}
                        </div>
                    </div>
                </div>
            </div>
        */}, {
            pid: ++pid,
            content: content,
            title: option.title,
            clsName: option.clsName,
            closeButton: option.closeButton || 'inner',  //'inner|outer|none'
            buttonStyle: option.buttonStyle,
            end: null
        }));
        
        $('body').append($container);
        
        var $windowPanel = $container.find('.jqWindowPanel');
        
        options[pid] = {
            onsubmit: option.onsubmit,
            onclose: option.onclose,
            $window: $windowPanel
        };
        
        var cssAttr = {};
        var hasAttr = false;
        $.each('width height'.split(' '), function(i, name){
            if(name in option){
                hasAttr = true;
                cssAttr[name] = option[name] +'px';
            }
        });
        
        if(hasAttr){
            $windowPanel.css(cssAttr);
        }
        
        if(openLength == 1){
            $('html').css('overflow-y', 'hidden');
            if(OVERFLOW_Y == 'scroll'){
                $('html').css('margin-right', SCROLL_WIDTH);
            }
        }
        
        $container.show();
        
        setPosition($windowPanel);
        
        return {
            close: function(){
                close($container);
            },
            submit: function(){
                submit($container);
            },
            refresh: function(){
                setPosition($windowPanel);
            }
        };
        
    }
    
    function close($container, button){
        
        openLength--;
        
        var pid = $container.attr('data-pid');
        var onclose = options[pid].onclose;
        onclose && onclose(button);
        delete options[pid];
        
        $container.remove();
        
        if(!openLength){ //恢复滚动条
            $('html').css('overflow-y', OVERFLOW_Y);
            if(OVERFLOW_Y == 'scroll'){
                $('html').css('margin-right', 0);
            }
        }
        
    }
    
    function submit($container, button){
        var onsubmit = options[$container.attr('data-pid')].onsubmit;
        if(!onsubmit || onsubmit &&
            onsubmit(button, function(){
                close($container, button);
            }) !== false //返回为false为异步，需要手动调用resolve
        ){
            close($container, button);
        }
    }
    
    function alert(msg, onclose){
        open('<div class="msgbox fs14">'+ msg +'</div><div class="buttonbox"><b jbtn="jqWindow.submit" class="ok">确定</b></div>', {title:'系统提示', clsName:'sysbox', onclose:onclose});
    }
    
    function confirm(msg, yes, no){
        open('<div class="msgbox fs14">'+ msg +'</div><div class="buttonbox"><b jbtn="jqWindow.submit" class="ok">确定</b><b jbtn="jqWindow.close" class="close">取消</b></div>', {title:'系统提示', clsName:'sysbox', onclose:no, onsubmit:yes});
    }
    
    function setPosition($windowPanel){
        $windowPanel.css({
            marginLeft: -$windowPanel.width() / 2,
            marginTop: -Math.min( window.innerHeight || document.documentElement.clientHeight, $windowPanel.height() ) / 2
        });
    }
    
    function getScrollSize(){
        var div = document.createElement('div');
        div.style.cssText = 'position:absolute; top:-99px; width:66px; height:66px;';
        document.body.appendChild(div);
        var width = div.clientWidth;
        div.style.overflow = 'scroll';
        width -= div.clientWidth;
        document.body.removeChild(div);
        return width;
    }
    
});

$$('alert', function(){
    return function(){
        $$.window.alert.apply(null, arguments);  
    };
});

$$('confirm', function(){
    return function(){
        $$.window.confirm.apply(null, arguments);  
    };
});


/*===== common/base#post:0 =====*/

$$.post = function(url, callback, data, option){
    
    option = option || {loaddingType: -1};
    var timeout = option.timeout || 600000;
    var loaddingText = option.loaddingText || '数据提交中，请稍后…';
    var loaddingType = option.loaddingType || 10;
    var tipsBox;
    var loaddingCtn = option.loaddingCtn;
    var postDataEscape = option.postDataEscape || false;
    var delay = option.delay >= 0 ? option.delay : 1000; //默认延迟时间
    var startTime = +new Date;

    if(loaddingType == -1){
    
    }else if(loaddingType == 1){
        
        tipsBox = $$.window.open($rtpl(function(){/*
            <div class="loadingShow">
                <p class="loadingGif"><i></i></p>
                <p>{{loaddingText}}</p>
            </div>
        */},{loaddingText:loaddingText}), {clsName:'lgWindow', title:'提示'});
    }else{
        tipsBox = $('<div class="jqPostTipbox"><div class="masklayer"></div><span class="tipstext">数据提交中，请稍后...</span></div>');
        if(loaddingCtn){
            tipsBox.css('position', 'absolute');
            $(loaddingCtn).append(tipsBox);
        }else{
            tipsBox.css('position', 'fixed');
            $('body').append(tipsBox);
        }
    }

    $.ajax({
        url:url,
        type:'post',
        data:data,
        dataType:'json',
        timeout:timeout,
        success:function(data){
            if(loaddingType == -1){
                if(data.result == 'success' || data.result === true){
                    callback(data);
                }else if(typeof data == 'object'){
                    data.err = data.msg || '数据错误';
                    callback(data);
                }else{
                    callback({
                        err: '数据格式错误，返回的数据不能为字符串！'
                    });
                }
            }else{
                setTimeout(function(){
                    if(loaddingType == 1){
                        tipsBox && tipsBox.close();
                    }else{
                        tipsBox && tipsBox.remove();
                    }
                    if(data.result == 'success' || data.result === true){
                        callback(data);
                    }else if(typeof data == 'object'){
                        data.err = data.msg || '数据错误';
                        callback(data);
                    }else{
                        callback({
                            err: '数据格式错误，返回的数据不能为字符串！'
                        });
                    }
                }, Math.max(0, delay - (+new Date - startTime) ) );
            }
            
        },
        error:function(data){
            setTimeout(function(){
                if(loaddingType == 1){
                    tipsBox && tipsBox.close();
                }else{
                    tipsBox && tipsBox.remove();
                }
                callback({
                    err: '请求异常'
                });
            }, 666);
        }
    });

};

/*===== common/base#qrcode:0 =====*/

$$.qrcode = function(){
    return function(selector, text, option){
        option = option || {};
        if(option.encode){
            text = toUtf8(text);
        }
        
        if(!document.createElement('canvas').getContext){
            option.render = 'table';
        }
        
        option.text = text;
        $(selector).qrcode(option);
    };
    
    function toUtf8(str) {    
        var out, i, len, c;    
        out = "";    
        len = str.length;    
        for(i = 0; i < len; i++) {    
            c = str.charCodeAt(i);    
            if ((c >= 0x0001) && (c <= 0x007F)) {    
                out += str.charAt(i);    
            } else if (c > 0x07FF) {    
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));    
                out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));    
                out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));    
            } else {    
                out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));    
                out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));    
            }    
        }    
        return out;    
    }
    
}();
